<template>
  <view class="container">
    <uni-nav-bar 
      :title="id ? '编辑工单' : '添加工单'" 
      left-icon="arrowleft" 
      @clickLeft="goBack"
    >
      <view slot="right" @click="handleSubmit" class="nav-right">
        <text>保存</text>
      </view>
    </uni-nav-bar>
    
    <scroll-view scroll-y class="form-container">
      <uni-card>
        <uni-section title="基本信息" type="line"></uni-section>
        
        <uni-forms ref="form" :modelValue="formData" :rules="rules">
          <!-- 集装箱号 -->
          <uni-forms-item label="集装箱号" required name="container_number">
            <uni-easyinput 
              v-model="formData.container_number" 
              placeholder="请输入集装箱号"
            />
          </uni-forms-item>
          
          <!-- 集装箱类型 -->
          <uni-forms-item label="集装箱类型" required name="container_type">
            <uni-data-select
              v-model="formData.container_type"
              :localdata="containerTypes"
              placeholder="请选择集装箱类型"
            ></uni-data-select>
          </uni-forms-item>
          
          <!-- 装货日期 -->
          <uni-forms-item label="装货日期" required name="loading_date">
            <uni-datetime-picker
              type="date"
              v-model="formData.loading_date"
              placeholder="请选择装货日期"
			  :clear-icon="false"
            />
          </uni-forms-item>
          
          <!-- 车辆信息 -->
          <uni-forms-item label="车辆信息" name="car">
            <uni-easyinput 
              v-model="formData.car" 
              placeholder="请输入车辆信息"
            />
          </uni-forms-item>
          
          <!-- 操作类型 -->
          <uni-forms-item label="操作类型" required name="order_type">
            <checkbox-group @change="handleOperationChange">
              <label class="checkbox-label" v-for="op in operations" :key="op">
                <checkbox :value="op" :checked="isOperationChecked(op)" />
                <text>{{ op }}</text>
              </label>
            </checkbox-group>
          </uni-forms-item>
          
          <uni-section title="位置信息" type="line"></uni-section>
          
          <!-- 提箱地点 -->
          <uni-forms-item label="提箱地点" name="pickup_location">
            <uni-easyinput 
              v-model="formData.pickup_location" 
              placeholder="请输入提箱地点"
            />
          </uni-forms-item>
          
          <!-- 还箱地点 -->
          <uni-forms-item label="还箱地点" name="dropoff_location">
            <uni-easyinput 
              v-model="formData.dropoff_location" 
              placeholder="请输入还箱地点"
            />
          </uni-forms-item>
          
          <!-- 门点位置 -->
          <uni-forms-item label="门点位置" name="loading_location">
            <uni-easyinput 
              v-model="formData.loading_location" 
              placeholder="请输入门点位置"
            />
          </uni-forms-item>
          
          <!-- GPS坐标 -->
          <uni-forms-item label="GPS坐标">
            <view class="gps-container">
              <uni-easyinput 
                v-model="formData.gps_latitude" 
                placeholder="纬度" 
                class="gps-input"
              />
              <uni-easyinput 
                v-model="formData.gps_longitude" 
                placeholder="经度" 
                class="gps-input"
              />
              <button class="mini-btn" type="primary" size="mini" @click="getLocation">
                获取位置
              </button>
            </view>
          </uni-forms-item>
          
          <uni-section title="费用信息" type="line"></uni-section>
          
          <!-- 提还箱费用 -->
          <uni-forms-item label="提还箱费用" name="pickup_return_fee">
            <uni-easyinput 
              v-model="formData.pickup_return_fee" 
              placeholder="请输入费用" 
              type="digit"
            >
              <template #right>
                <text class="input-right">元</text>
              </template>
            </uni-easyinput>
          </uni-forms-item>
          
          <uni-section title="其他信息" type="line"></uni-section>
          
          <!-- 备注 -->
          <uni-forms-item label="备注" name="remarks">
            <uni-easyinput 
              v-model="formData.remarks" 
              placeholder="请输入备注" 
              type="textarea"
            />
          </uni-forms-item>
          
          <!-- 照片上传 -->
          <uni-forms-item label="照片">
            <uni-file-picker 
              :value="fileList" 
              fileMediatype="image" 
              mode="grid"
              limit="1"
              @select="handleFileSelect"
              @delete="handleFileDelete"
            ></uni-file-picker>
            <image 
              v-if="formData.photo_path" 
              :src="getFullImageUrl(formData.photo_path)" 
              mode="aspectFit" 
              class="preview-image"
              @click="previewImage"
            />
          </uni-forms-item>
        </uni-forms>
      </uni-card>
    </scroll-view>
  </view>
</template>

<script>
import api from '@/store/work_api.js';
import uniNavBar from '@dcloudio/uni-ui/lib/uni-nav-bar/uni-nav-bar.vue';
import uniCard from '@dcloudio/uni-ui/lib/uni-card/uni-card.vue';
import uniSection from '@dcloudio/uni-ui/lib/uni-section/uni-section.vue';
import uniForms from '@dcloudio/uni-ui/lib/uni-forms/uni-forms.vue';
import uniFormsItem from '@dcloudio/uni-ui/lib/uni-forms-item/uni-forms-item.vue';
import uniEasyinput from '@dcloudio/uni-ui/lib/uni-easyinput/uni-easyinput.vue';
import uniDataSelect from '@dcloudio/uni-ui/lib/uni-data-select/uni-data-select.vue';
import uniDatetimePicker from '@dcloudio/uni-ui/lib/uni-datetime-picker/uni-datetime-picker.vue';
import uniFilePicker from '@dcloudio/uni-ui/lib/uni-file-picker/uni-file-picker.vue';

export default {
  components: {
    uniNavBar,
    uniCard,
    uniSection,
    uniForms,
    uniFormsItem,
    uniEasyinput,
    uniDataSelect,
    uniDatetimePicker,
    uniFilePicker
  },
  data() {
    return {
      id: '', // 编辑时传入的ID
      formData: {
        container_number: '',
        container_type: '',
        loading_date: '',
        car: '',
        order_type: [],
        pickup_location: '',
        dropoff_location: '',
        loading_location: '',
        gps_latitude: '0',
        gps_longitude: '0',
        pickup_return_fee: '',
        remarks: '',
        photo_path: ''
      },
	  fileList: [], // 用于 uni-file-picker 的文件列表
      containerTypes: [
        { value: '20GP', text: '20GP' },
        { value: '20HC', text: '20HC' },
        { value: '40GP', text: '40GP' },
        { value: '40HC', text: '40HC' },
        { value: '40HQ', text: '40HQ' },
		{ value: '40RT', text: '40RT' },
		{ value: '40TR', text: '40TR' },
        { value: '45GP', text: '45GP' },
        { value: '45HQ', text: '45HQ' },
        { value: 'OTHER', text: '其他' }
      ],
      operations: ['提箱', '装货', '卸货', '进港'],
      rules: {
        container_number: {
          rules: [{
            required: true,
            errorMessage: '请输入集装箱号'
          }]
        },
        container_type: {
          rules: [{
            required: true,
            errorMessage: '请选择集装箱类型'
          }]
        },
        loading_date: {
          rules: [{
            required: true,
            errorMessage: '请选择装货日期'
          }]
        },
        order_type: {
          rules: [{
            validateFunction: (rule, value, data, callback) => {
              if (!value || value.length === 0) {
                callback('请至少选择一项操作类型');
              }
              return true;
            }
          }]
        }
      }
    }
  },
  onLoad(options) {
    if (options.id) {
      this.id = options.id;
      this.loadDetail();
    }else {
      // 添加模式下的默认值设置
      this.setDefaultValues();
    }
  },
  methods: {
	setDefaultValues() {
	      // 1. 设置当前日期为装货日期
	      const today = new Date();
	      this.formData.loading_date = this.formatDate(today, 'YYYY-MM-DD');
	      
	      // 2. 从用户资料中获取车辆信息
	      const userInfo = uni.getStorageSync('user') || {};
	      this.formData.car = userInfo.car || '';
		  
		  // 3. 尝试获取当前位置
		  this.getLocation();
	    },
	    
	    // 日期格式化方法（如果尚未定义）
	    formatDate(date, fmt) {
	      const o = {
	        'M+': date.getMonth() + 1,
	        'D+': date.getDate(),
	        'h+': date.getHours(),
	        'm+': date.getMinutes(),
	        's+': date.getSeconds()
	      };
	      if (/(Y+)/.test(fmt)) {
	        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
	      }
	      for (let k in o) {
	        if (new RegExp(`(${k})`).test(fmt)) {
	          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
	        }
	      }
	      return fmt;
	    },
		// 修改获取位置方法
		    getLocation() {
		      uni.getLocation({
		        type: 'wgs84',
		        success: (res) => {
		          this.formData.gps_latitude = res.latitude.toFixed(6);
		          this.formData.gps_longitude = res.longitude.toFixed(6);
		          uni.showToast({
		            title: '位置获取成功',
		            icon: 'success'
		          });
		        },
		        fail: (err) => {
		          // 设置默认空值
		          this.formData.gps_latitude = '0';
		          this.formData.gps_longitude = '0';
		          // 不显示错误提示，因为可能是用户未授权
		        }
		      });
		    },
    // 加载详情数据
    async loadDetail() {
      uni.showLoading({ title: '加载中...' });
      try {
        const res = await api.getWorkRecordDetail(this.id);
        if (res.data.status === 'success') {
          const detail = res.data.data;
          // 格式化数据
          this.formData = {
            ...this.formData,
            ...detail,
            order_type: detail.order_type ? 
              (typeof detail.order_type === 'string' ? 
                detail.order_type.split(',') : 
                detail.order_type) : 
              []
          };
		  // 初始化文件列表
		  if (this.formData.photo_path) {
			  this.fileList = [{
				url: this.getFullImageUrl(this.formData.photo_path),
				extname: this.formData.photo_path.split('.').pop(),
				name: this.formData.photo_path.split('/').pop()
			  }];
			}
        } else {
          throw new Error(res.data.message || '加载失败');
        }
      } catch (err) {
        uni.showToast({
          title: err.message || '加载失败',
          icon: 'none'
        });
        setTimeout(() => this.goBack(), 1500);
      } finally {
        uni.hideLoading();
      }
    },
    
    // 检查操作是否选中
    isOperationChecked(operation) {
      return this.formData.order_type.includes(operation);
    },
    
    // 处理操作类型变化
    handleOperationChange(e) {
      this.formData.order_type = e.detail.value;
    },
    
    // 获取当前位置
    getLocation() {
      uni.getLocation({
        type: 'wgs84',
        success: (res) => {
          this.formData.gps_latitude = res.latitude.toFixed(6);
          this.formData.gps_longitude = res.longitude.toFixed(6);
          uni.showToast({
            title: '位置获取成功',
            icon: 'success'
          });
        },
        fail: (err) => {
          uni.showToast({
            title: '获取位置失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 处理文件选择
    async handleFileSelect(e) {
      const file = e.tempFiles[0];
      try {
        uni.showLoading({ title: '图片上传中...', mask: true });
        
        // 修改1：不使用数组解构，直接接收返回值
        const uploadRes = await uni.uploadFile({
          url: 'http://192.168.1.42:8000/api/workupload.php',
          filePath: file.path,
          name: 'file',
          formData: { type: 'work_order' },
        });
    
        
        // 修改2：兼容不同版本的返回值结构
        const response = uploadRes[1] || uploadRes; // 如果是数组取第二个元素，否则直接使用
        
        // 修改3：更安全的JSON解析
        let responseData;
        try {
          responseData = typeof response.data === 'string' ? 
                        JSON.parse(response.data) : 
                        response.data;
        } catch (parseError) {
          console.error('解析响应数据失败:', parseError);
          console.error('原始响应数据:', response);
          throw new Error('服务器返回数据格式错误');
        }
    
        // 检查上传结果
        if (!responseData || responseData.code !== 200) {
          throw new Error(responseData?.message || '图片上传失败');
        }
    
        // 确保路径存在
        if (!responseData.data?.path) {
          throw new Error('服务器未返回有效文件路径');
        }
    
        // 更新数据
        this.formData.photo_path = responseData.data.path;
        this.fileList = [{
          url: this.getFullImageUrl(responseData.data.path),
          name: file.name,
          extname: file.ext
        }];
        
        uni.showToast({ title: '图片上传成功', icon: 'success' });
      } catch (err) {
        console.error('图片上传失败:', err);
        uni.showToast({ 
          title: '图片上传失败: ' + (err.message || '未知错误'), 
          icon: 'none',
          duration: 3000
        });
        this.fileList = [];
      } finally {
        uni.hideLoading();
      }
    },
	
    // 处理文件删除
    handleFileDelete() {
      this.formData.photo_path = '';
	  this.fileList = [];
    },
    
    // 预览图片
    previewImage() {
      if (!this.formData.photo_path) return;
      uni.previewImage({
        urls: [this.getFullImageUrl(this.formData.photo_path)]
      });
    },
    
    // 获取完整图片URL
    getFullImageUrl(path) {
      if (!path) return '';
      // 临时路径直接使用
      if (path.startsWith('http') || path.includes('tmp')) {
        return path;
      }
      // 服务器路径添加基础URL
      return 'http://192.168.1.42:8000/' + path.replace(/\\/g, '/').replace(/^\//, '');
    },
    
    // 提交表单
    async handleSubmit() {
      try {
        // 1. 表单验证
        await this.$refs.form.validate();
        uni.showLoading({ title: '提交中...', mask: true });
    
        const submitData = {
          container_number: this.formData.container_number,
          container_type: this.formData.container_type,
          loading_date: this.formData.loading_date,
          car: this.formData.car || '',
          order_type: Array.isArray(this.formData.order_type) 
            ? this.formData.order_type.join(',') 
            : '',
          pickup_location: this.formData.pickup_location || '',
          dropoff_location: this.formData.dropoff_location || '',
          loading_location: this.formData.loading_location || '',
          gps_latitude: Number(this.formData.gps_latitude) || 0,
          gps_longitude: Number(this.formData.gps_longitude) || 0,
          pickup_return_fee: Number(this.formData.pickup_return_fee) || 0,
          remarks: this.formData.remarks || '',
          photo_path: this.formData.photo_path || '',
          user_id: uni.getStorageSync('user')?.id || 0
        };
    
        // 3. 根据模式调用API
        let apiResponse;
        if (this.id) {
          // 编辑模式
          apiResponse = await api.updateWorkRecord({ 
            ...submitData, 
            id: this.id 
          });
        } else {
          // 添加模式
          apiResponse = await api.addWorkRecord(submitData);
        }
    
        if (!apiResponse.data) {
          throw new Error('API返回数据为空');
        }
    
        if (apiResponse.data.status === 'success') {
          uni.showToast({
            title: `${this.id ? '更新' : '添加'}成功`,
            icon: 'success'
          });
          
          // 返回并刷新列表
          setTimeout(() => {
            uni.navigateBack();
            uni.$emit('refreshWorkList');
          }, 1500);
        } else {
          // 显示服务器返回的具体错误信息
          throw new Error(apiResponse.data.message || '操作失败');
        }
      } catch (error) {
        console.error('操作失败详情:', error);
        
        // 更友好的错误提示
        let errorMessage = error.message;
        if (error.message.includes('Network Error')) {
          errorMessage = '网络连接失败，请检查网络';
        } else if (error.message.includes('timeout')) {
          errorMessage = '请求超时，请重试';
        }
    
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 上传图片方法
    async uploadImage(filePath) {
      const res = await uni.uploadFile({
        url: 'http://192.168.1.42:8000/api/workupload.php',
        filePath,
        name: 'file',
        formData: { type: 'work_order' }
      });
      return JSON.parse(res[1].data); // 假设返回 { status: 'success', filePath: '...' }
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.nav-right {
  padding-right: 20rpx;
  color: #007aff;
}

.form-container {
  flex: 1;
  padding: 20rpx;
}

.checkbox-label {
  margin-right: 30rpx;
  display: inline-flex;
  align-items: center;
}

.checkbox-label text {
  margin-left: 10rpx;
}

.gps-container {
  display: flex;
  align-items: center;
}

.gps-input {
  flex: 1;
  margin-right: 10rpx;
}

.mini-btn {
  margin-left: 10rpx;
}

.input-right {
  padding: 0 10rpx;
  color: #999;
}

.preview-image {
  width: 200rpx;
  height: 200rpx;
  margin-top: 20rpx;
  border-radius: 8rpx;
}
</style>